// 用户模块
import { userAccountLogin, userMobileLogin, userQQBindLogin, userQQPatchLogin } from '@/api/user.js'
export default {
  namespaced: true,
  state () {
    return {
      // 用户信息
      profile: {
        id: '',
        avatar: '',
        nickname: '',
        account: '',
        mobile: '',
        token: ''
      }
    }
  },
  mutations: {
    // 修改用户信息，payload就是用户信息对象
    setUser (state, payload) {
      state.profile = payload
    }
  },
  actions: {
    // 账号密码登录
    async userAccountLogin (ctx, user) {
      // 发ajax
      console.log('userAccountLogin', user)
      try {
        const data = await userAccountLogin(user)
        // 保存数据
        ctx.commit('setUser', data.result)
      } catch (err) {
        console.dir(err)
        const msg = err.response.data.message || '登录失败'
        throw new Error(msg)
      }
    },
    // 账号密码登录
    async userMobileLogin (ctx, { mobile, code }) {
      // 发ajax
      console.log('userMobileLogin', { mobile, code })
      try {
        const data = await userMobileLogin({ mobile, code })
        // 保存数据
        ctx.commit('setUser', data.result)
      } catch (err) {
        console.dir(err)
        const msg = err.response.data.message || '登录失败'
        throw new Error(msg)
      }
    },

    // 登录qq绑定已有账号
    async userQQBindLogin (ctx, { unionId, mobile, code }) {
      // 发ajax
      console.log('userQQBindLogin', { unionId, mobile, code })
      try {
        const data = await userQQBindLogin({ unionId, mobile, code })
        // 保存数据
        ctx.commit('setUser', data.result)
      } catch (err) {
        console.dir(err)
        const msg = err.response.data.message || '绑定失败'
        throw new Error(msg)
      }
    },
    // 登录qq补充新账号
    async userQQPatchLogin (ctx, { unionId, mobile, code, account, password }) {
      // 发ajax
      console.log('userMobileLogin', { unionId, mobile, code, account, password })
      try {
        const data = await userQQPatchLogin({ unionId, mobile, code, account, password })
        // 保存数据
        ctx.commit('setUser', data.result)
      } catch (err) {
        console.dir(err)
        const msg = err.response.data.message || '绑定失败'
        throw new Error(msg)
      }
    }
  }
}
